package com.solotiger.douban.common;

import android.support.v4.app.FragmentManager;

import com.solotiger.douban.ui.fragment.LoadingViewFragment;


public class CommonDialogManager {

    private LoadingViewFragment mLoadingFragment;

    private Integer mInt;

    public CommonDialogManager() {
        mInt = 0;
    }


    private void showBlockingDialog(FragmentManager manager , boolean canCancel) {
        if (mLoadingFragment == null) {
            mLoadingFragment = LoadingViewFragment.newInstance();
        }
        if (mLoadingFragment.isAdded()) {
            return;
        }
        mLoadingFragment.setCancel(canCancel);
        mLoadingFragment.show(manager, LoadingViewFragment.TAG);
    }


    public void lockLoadData(FragmentManager manager) {
        lockLoadData(manager ,true);
    }

    public void lockLoadData(FragmentManager manager , boolean canCancel) {
        synchronized (mInt) {
            if (mInt < 0)
                mInt = 0;
            mInt++;
            showBlockingDialog(manager , canCancel);
        }
    }

    /**
     * 解锁:UI UN阻塞
     */
    public void unlockLoadData() {
        synchronized (mInt) {
            if (mInt > 0) {
                mInt--;
                if (mInt == 0) {
                    dismissBlockingProgress();
                }
            } else {
                dismissBlockingProgress();
            }
        }
    }

    protected void dismissBlockingProgress() {
        try {
            if (mLoadingFragment != null) {
                mLoadingFragment.dismissAllowingStateLoss();
                mLoadingFragment = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
